package com.lonely.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.api.mes.model.dto.MesReportWorkDTO;
import com.lonely.api.mes.model.vo.MesReportWorkVO;
import com.lonely.api.mes.service.ISynchronizedMesService;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.order.domain.entity.SysReportWork;
import com.lonely.order.domain.vo.order.ReportWorkVO;
import com.lonely.order.mapper.SysReportWorkMapper;
import com.lonely.order.service.IReportWorkService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/11/18 17:04
 * @description: 订单报工服务实现类
 */
@Service
public class ReportWorkServiceImpl extends ServiceImpl<SysReportWorkMapper, SysReportWork> implements IReportWorkService {

    @Autowired
    private ISynchronizedMesService synchronizedMesService;

    /**
     * 获取某个订单的报工记录
     *
     * @param produceOrderId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ReportWorkVO> getReportWorkByProduceOrderId(String produceOrderId) {
        MesReportWorkDTO mesReportWorkDTO = new MesReportWorkDTO();
        mesReportWorkDTO.setOrderPno(produceOrderId);
        MesReportWorkVO mesReportWorkVO = this.synchronizedMesService.reportWork(mesReportWorkDTO);
        if (mesReportWorkVO == null) {
            return new ArrayList<>();
        }

        // 先移除该订单的报工记录
        super.getBaseMapper().physicalDeletionByProduceOrderId(produceOrderId);

        // 新增数据
        List<SysReportWork> reportWorks = mesReportWorkVO.getLineList().stream().map(x -> {
            SysReportWork reportWorkVO = new SysReportWork();
            BeanUtils.copyProperties(x, reportWorkVO);
            reportWorkVO.setCreateBy(SecurityUtils.getUserId());
            reportWorkVO.setUpdateBy(SecurityUtils.getUserId());
            return reportWorkVO;
        }).collect(Collectors.toList());
        super.saveBatch(reportWorks);

        return reportWorks.stream().map(x -> {
            ReportWorkVO reportWorkVO = new ReportWorkVO();
            BeanUtils.copyProperties(x, reportWorkVO);
            return reportWorkVO;
        }).collect(Collectors.toList());
    }
}
